From 5e5b67e5b98d3183044dc5149fe67a29feeb3c41 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Mon, 10 Jun 2024 16:53:28 +0700
Subject: <iman> update promotion-program

---
 src/pages/shop/promo/[slug].tsx | 161 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 161 insertions(+)
 create mode 100644 src/pages/shop/promo/[slug].tsx

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
new file mode 100644
index 00000000..cd3e93c4
--- /dev/null
+++ b/src/pages/shop/promo/[slug].tsx
@@ -0,0 +1,161 @@
+import dynamic from 'next/dynamic'
+import { useEffect, useState } from 'react'
+import { useRouter } from 'next/router'
+import Seo from '../../../core/components/Seo'
+import Promocrumb from '../../../lib/promo/components/Promocrumb'
+import { fetchPromoItemsSolr } from '../../../api/promoApi'
+import LogoSpinner from '../../../core/components/elements/Spinner/LogoSpinner.jsx'
+import ProductPromoCard from '../../../../src-migrate/modules/product-promo/components/Card'
+import { IPromotion } from '../../../../src-migrate/types/promotion'
+import React from 'react'
+import { SolrResponse } from "../../../../src-migrate/types/solr.ts";
+
+
+const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout'))
+
+export default function PromoDetail() {
+  const router = useRouter()
+  const { slug = '' } = router.query
+  const [promoItems, setPromoItems] = useState<any[]>([])
+  const [promoData, setPromoData] = useState<IPromotion[] | null>(null)
+  const [currentPage, setCurrentPage] = useState(1);
+  const itemsPerPage = 12; // Jumlah item yang ingin ditampilkan per halaman
+  const startIndex = (currentPage - 1) * itemsPerPage;
+  const endIndex = Math.min(startIndex + itemsPerPage, promoData?.length || 0);
+  const visiblePromotions = promoData?.slice(startIndex, endIndex);
+  const [loading, setLoading] = useState(true); // Menambahkan status loading
+
+
+  useEffect(() => {
+    const loadPromo = async () => {
+      try {
+        const items = await fetchPromoItemsSolr(Array.isArray(slug) ? slug[0] : slug)
+        console.log("slug sekarang ", slug)
+        
+        setPromoItems(items)
+        console.log("data dari promotion pakai SOLR", items)
+
+        if (items.length === 0) {
+          setPromoData([])
+          setLoading(false);
+          return;
+        }
+
+        const promoDataPromises = items.map(async (item) => {
+          const queryParams = new URLSearchParams({ q: `id:${item.id}` })
+          console.log("Constructed URL:", `/solr/promotion_program_lines/select?${queryParams.toString()}`)
+
+          try {
+            const response = await fetch(`/solr/promotion_program_lines/select?${queryParams.toString()}`)
+            console.log("respon data ", response)
+            if (!response.ok) {
+              throw new Error(`HTTP error! status: ${response.status}`)
+            }
+
+            const data: SolrResponse<any[]> = await response.json()
+            console.log("data promo IPromotion[]", data)
+            
+            const promotions = await map(data.response.docs)
+            return promotions;
+          } catch (fetchError) {
+            console.error("Error fetching promotion data:", fetchError)
+            return [];
+          }
+        });
+
+        const promoDataArray = await Promise.all(promoDataPromises);
+        const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
+        setPromoData(mergedPromoData);
+        setTimeout(() => setLoading(false), 120); // Menambahkan delay 200ms sebelum mengubah status loading
+      } catch (loadError) {
+        console.error("Error loading promo items:", loadError)
+        setLoading(false);
+      }
+    }
+
+    if (slug) {
+      loadPromo()
+    }
+  }, [slug])
+
+  useEffect(() => {
+    window.scrollTo({ top: 0, behavior: 'auto' }); // Auto scroll to top when component mounts or updates
+  }, []); // Run only once when component mounts
+  
+
+  const map = async (promotions: any[]): Promise<IPromotion[]> => {
+    const result: IPromotion[] = []
+  
+    for (const promotion of promotions) {
+      const data: IPromotion = {
+        id: promotion.id,
+        program_id: promotion.program_id_i,
+        name: promotion.name_s,
+        type: {
+          value: promotion.type_value_s,
+          label: promotion.type_label_s,
+        },
+        limit: promotion.package_limit_i,
+        limit_user: promotion.package_limit_user_i,
+        limit_trx: promotion.package_limit_trx_i,
+        price: promotion.price_f,
+        total_qty: promotion.total_qty_i,
+        products: JSON.parse(promotion.products_s),
+        free_products: JSON.parse(promotion.free_products_s),
+      }
+  
+      result.push(data)
+    }
+  
+    return result
+  }
+
+  console.log("data yg dikirim ke ProductPromoCard", promoData)
+  function capitalizeFirstLetter(string) {
+    return string.charAt(0).toUpperCase() + string.slice(1);
+  }
+
+  const goToNextPage = () => {
+    setCurrentPage((prevPage) => prevPage + 1);
+    window.scrollTo({ top: 0, behavior: 'smooth' });
+  };
+  
+  const goToPreviousPage = () => {
+    setCurrentPage((prevPage) => Math.max(prevPage - 1, 1));
+    window.scrollTo({ top: 0, behavior: 'smooth' });
+  };
+  
+  return (
+    <BasicLayout>
+      <Seo
+        title={`Promo ${Array.isArray(slug) ? slug[0] : slug} Terkini`} 
+        description='B2B Marketplace MRO & Industri dengan Layanan Pembayaran Tempo, Faktur Pajak, Online Quotation, Garansi Resmi & Harga Kompetitif'
+      />
+      <Promocrumb brandName={capitalizeFirstLetter(Array.isArray(slug) ? slug[0] : slug)} /> 
+
+      {loading ? (
+        <div className='container flex justify-center my-4'>
+        <LogoSpinner width={48} height={48} />
+      </div>
+      ) : promoData && promoItems.length >= 1 ? (
+        <>
+          <div className='flex flex-wrap justify-center'>
+            {visiblePromotions?.map((promotion) => (
+              <div key={promotion.id} className="min-w-[40px] max-w-[400px] mr-[20px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
+                <ProductPromoCard promotion={promotion} slug={Array.isArray(slug) ? slug[0] : slug} />
+              </div>
+            ))}
+          </div>
+          <div className="flex justify-center mt-4">
+            <button onClick={goToPreviousPage} disabled={currentPage === 1} className="mr-2 px-4 py-2 bg-gray-200 rounded">Back</button>
+            <button onClick={goToNextPage} disabled={endIndex >= promoData.length} className="px-4 py-2 bg-gray-200 rounded">Next</button>
+          </div>
+        </>
+      ) : (
+        <div className="text-center my-8">
+          <p>Belum ada promo pada kategori ini</p>
+        </div>
+      )}
+    </BasicLayout>
+  )
+}
\ No newline at end of file
-- 
cgit v1.2.3


From 9565ddf794165e297acf511a108f9a9643ee615d Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Tue, 11 Jun 2024 13:40:23 +0700
Subject: <iman> update promotion program

---
 src/pages/shop/promo/[slug].tsx | 77 ++++++++++++++++++++++++++++++++---------
 1 file changed, 60 insertions(+), 17 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index cd3e93c4..be5a715d 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -10,7 +10,6 @@ import { IPromotion } from '../../../../src-migrate/types/promotion'
 import React from 'react'
 import { SolrResponse } from "../../../../src-migrate/types/solr.ts";
 
-
 const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout'))
 
 export default function PromoDetail() {
@@ -22,14 +21,15 @@ export default function PromoDetail() {
   const itemsPerPage = 12; // Jumlah item yang ingin ditampilkan per halaman
   const startIndex = (currentPage - 1) * itemsPerPage;
   const endIndex = Math.min(startIndex + itemsPerPage, promoData?.length || 0);
-  const visiblePromotions = promoData?.slice(startIndex, endIndex);
+  // const visiblePromotions = promoData?.slice(startIndex, endIndex);
   const [loading, setLoading] = useState(true); // Menambahkan status loading
+  const [fetchingData, setFetchingData] = useState(false)
 
 
   useEffect(() => {
     const loadPromo = async () => {
       try {
-        const items = await fetchPromoItemsSolr(Array.isArray(slug) ? slug[0] : slug)
+        const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`)
         console.log("slug sekarang ", slug)
         
         setPromoItems(items)
@@ -112,18 +112,60 @@ export default function PromoDetail() {
 
   console.log("data yg dikirim ke ProductPromoCard", promoData)
   function capitalizeFirstLetter(string) {
-    return string.charAt(0).toUpperCase() + string.slice(1);
+    // Ganti semua tanda _ dengan spasi
+    string = string.replace(/_/g, ' ');
+    
+    // Kapitalisasi huruf pertama setelah spasi atau awal string
+    return string.replace(/(^\w|\s\w)/g, function(match) {
+        return match.toUpperCase();
+    });
+
+
+  }
+
+  useEffect(() => {
+    const handleScroll = () => {
+      if (
+        !fetchingData &&
+        window.innerHeight + document.documentElement.scrollTop >= 0.95 * document.documentElement.offsetHeight
+      ) {
+        // User has scrolled to 95% of page height
+        
+        setTimeout(() => setFetchingData(true), 120);
+        setCurrentPage((prevPage) => prevPage + 1)
+      }
+    }
+
+    window.addEventListener('scroll', handleScroll)
+    return () => window.removeEventListener('scroll', handleScroll)
+  }, [fetchingData])
+
+  useEffect(() => {
+    if (fetchingData) {
+      // Fetch more data
+      // You may need to adjust this logic according to your API
+      fetchMoreData()
+    }
+  }, [fetchingData])
+
+  const fetchMoreData = async () => {
+    try {
+      // Add a delay of approximately 150ms
+      setTimeout(async () => {
+        // Fetch more data
+        // Update promoData state with the new data
+      }, 150)
+    } catch (error) {
+      console.error('Error fetching more data:', error)
+    } finally {
+      setTimeout(() => setFetchingData(false), 120);
+      
+    }
   }
 
-  const goToNextPage = () => {
-    setCurrentPage((prevPage) => prevPage + 1);
-    window.scrollTo({ top: 0, behavior: 'smooth' });
-  };
+  const visiblePromotions = promoData?.slice(0, currentPage * 12)
+
   
-  const goToPreviousPage = () => {
-    setCurrentPage((prevPage) => Math.max(prevPage - 1, 1));
-    window.scrollTo({ top: 0, behavior: 'smooth' });
-  };
   
   return (
     <BasicLayout>
@@ -142,14 +184,15 @@ export default function PromoDetail() {
           <div className='flex flex-wrap justify-center'>
             {visiblePromotions?.map((promotion) => (
               <div key={promotion.id} className="min-w-[40px] max-w-[400px] mr-[20px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
-                <ProductPromoCard promotion={promotion} slug={Array.isArray(slug) ? slug[0] : slug} />
+                <ProductPromoCard promotion={promotion}/>
               </div>
             ))}
           </div>
-          <div className="flex justify-center mt-4">
-            <button onClick={goToPreviousPage} disabled={currentPage === 1} className="mr-2 px-4 py-2 bg-gray-200 rounded">Back</button>
-            <button onClick={goToNextPage} disabled={endIndex >= promoData.length} className="px-4 py-2 bg-gray-200 rounded">Next</button>
-          </div>
+          {fetchingData && (
+            <div className='container flex justify-center my-4'>
+              <LogoSpinner width={48} height={48} />
+            </div>
+          )}
         </>
       ) : (
         <div className="text-center my-8">
-- 
cgit v1.2.3


From ce968fcd38e5c4bb69400862fe4da484934088d5 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Tue, 11 Jun 2024 16:14:07 +0700
Subject: <iman? update promotion-program add swiper

---
 src/pages/shop/promo/[slug].tsx | 40 +++++++++++++++++++---------------------
 1 file changed, 19 insertions(+), 21 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index be5a715d..a2b790ca 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -9,6 +9,9 @@ import ProductPromoCard from '../../../../src-migrate/modules/product-promo/comp
 import { IPromotion } from '../../../../src-migrate/types/promotion'
 import React from 'react'
 import { SolrResponse } from "../../../../src-migrate/types/solr.ts";
+import { Swiper, SwiperSlide } from 'swiper/react';
+import 'swiper/swiper-bundle.css';
+import useDevice from '../../../core/hooks/useDevice'
 
 const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout'))
 
@@ -21,10 +24,9 @@ export default function PromoDetail() {
   const itemsPerPage = 12; // Jumlah item yang ingin ditampilkan per halaman
   const startIndex = (currentPage - 1) * itemsPerPage;
   const endIndex = Math.min(startIndex + itemsPerPage, promoData?.length || 0);
-  // const visiblePromotions = promoData?.slice(startIndex, endIndex);
-  const [loading, setLoading] = useState(true); // Menambahkan status loading
+  const [loading, setLoading] = useState(true);
   const [fetchingData, setFetchingData] = useState(false)
-
+  const { isMobile, isDesktop } = useDevice()
 
   useEffect(() => {
     const loadPromo = async () => {
@@ -66,7 +68,7 @@ export default function PromoDetail() {
         const promoDataArray = await Promise.all(promoDataPromises);
         const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
         setPromoData(mergedPromoData);
-        setTimeout(() => setLoading(false), 120); // Menambahkan delay 200ms sebelum mengubah status loading
+        setTimeout(() => setLoading(false), 120); // Menambahkan delay 120ms sebelum mengubah status loading
       } catch (loadError) {
         console.error("Error loading promo items:", loadError)
         setLoading(false);
@@ -82,7 +84,6 @@ export default function PromoDetail() {
     window.scrollTo({ top: 0, behavior: 'auto' }); // Auto scroll to top when component mounts or updates
   }, []); // Run only once when component mounts
   
-
   const map = async (promotions: any[]): Promise<IPromotion[]> => {
     const result: IPromotion[] = []
   
@@ -119,8 +120,6 @@ export default function PromoDetail() {
     return string.replace(/(^\w|\s\w)/g, function(match) {
         return match.toUpperCase();
     });
-
-
   }
 
   useEffect(() => {
@@ -162,11 +161,10 @@ export default function PromoDetail() {
       
     }
   }
-
+  
+    
   const visiblePromotions = promoData?.slice(0, currentPage * 12)
 
-  
-  
   return (
     <BasicLayout>
       <Seo
@@ -177,22 +175,22 @@ export default function PromoDetail() {
 
       {loading ? (
         <div className='container flex justify-center my-4'>
-        <LogoSpinner width={48} height={48} />
-      </div>
+          <LogoSpinner width={48} height={48} />
+        </div>
       ) : promoData && promoItems.length >= 1 ? (
         <>
-          <div className='flex flex-wrap justify-center'>
+          <Swiper slidesPerView={isMobile? 1:4.7} spaceBetween={10} freeMode={true}>
+            <div className=' relative bg-slate-900'>
             {visiblePromotions?.map((promotion) => (
-              <div key={promotion.id} className="min-w-[40px] max-w-[400px] mr-[20px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
-                <ProductPromoCard promotion={promotion}/>
-              </div>
+              <SwiperSlide className='' key={promotion.id}>
+                <div className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
+                  <ProductPromoCard promotion={promotion}/>
+                </div>
+              </SwiperSlide>
             ))}
+            
           </div>
-          {fetchingData && (
-            <div className='container flex justify-center my-4'>
-              <LogoSpinner width={48} height={48} />
-            </div>
-          )}
+          </Swiper>
         </>
       ) : (
         <div className="text-center my-8">
-- 
cgit v1.2.3


From 0a87455727114468c216fbcd74266ea928eaec37 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Thu, 13 Jun 2024 09:34:24 +0700
Subject: <iman> update promotion-program

---
 src/pages/shop/promo/[slug].tsx | 243 +++++++++++++++++++++++++---------------
 1 file changed, 153 insertions(+), 90 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index a2b790ca..1935c61f 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -3,21 +3,26 @@ import { useEffect, useState } from 'react'
 import { useRouter } from 'next/router'
 import Seo from '../../../core/components/Seo'
 import Promocrumb from '../../../lib/promo/components/Promocrumb'
-import { fetchPromoItemsSolr } from '../../../api/promoApi'
+import { fetchPromoItemsSolr, fetchVariantSolr } from '../../../api/promoApi'
 import LogoSpinner from '../../../core/components/elements/Spinner/LogoSpinner.jsx'
 import ProductPromoCard from '../../../../src-migrate/modules/product-promo/components/Card'
 import { IPromotion } from '../../../../src-migrate/types/promotion'
 import React from 'react'
 import { SolrResponse } from "../../../../src-migrate/types/solr.ts";
-import { Swiper, SwiperSlide } from 'swiper/react';
+import DesktopView from '../../../core/components/views/DesktopView';
 import 'swiper/swiper-bundle.css';
 import useDevice from '../../../core/hooks/useDevice'
+import ProductFilterDesktop from '../../../lib/product/components/ProductFilterDesktop';
+import { HStack, Image, Tag, TagCloseButton, TagLabel } from '@chakra-ui/react';
+import { formatCurrency } from '../../../core/utils/formatValue';
+import Pagination from '../../../core/components/elements/Pagination/Pagination';
+import { cons } from 'lodash-contrib'
 
 const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout'))
 
 export default function PromoDetail() {
   const router = useRouter()
-  const { slug = '' } = router.query
+  const { slug = '', brand, category } = router.query
   const [promoItems, setPromoItems] = useState<any[]>([])
   const [promoData, setPromoData] = useState<IPromotion[] | null>(null)
   const [currentPage, setCurrentPage] = useState(1);
@@ -25,42 +30,95 @@ export default function PromoDetail() {
   const startIndex = (currentPage - 1) * itemsPerPage;
   const endIndex = Math.min(startIndex + itemsPerPage, promoData?.length || 0);
   const [loading, setLoading] = useState(true);
-  const [fetchingData, setFetchingData] = useState(false)
   const { isMobile, isDesktop } = useDevice()
+  const [brands, setBrands] = useState<Brand[]>([]);
+  const [categories, setCategories] = useState<Category[]>([]);
+
+  interface Brand {
+    brand: string;
+    qty: number;
+  }
+
+  interface Category {
+    name: string;
+    qty: number;
+  }
 
   useEffect(() => {
     const loadPromo = async () => {
+      setLoading(true);
+      const brandsData: Brand[] = [];
+      const categoriesData: Category[] = [];
+
+      
       try {
         const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`)
-        console.log("slug sekarang ", slug)
-        
         setPromoItems(items)
-        console.log("data dari promotion pakai SOLR", items)
-
+        
         if (items.length === 0) {
           setPromoData([])
           setLoading(false);
           return;
-        }
-
-        const promoDataPromises = items.map(async (item) => {
-          const queryParams = new URLSearchParams({ q: `id:${item.id}` })
-          console.log("Constructed URL:", `/solr/promotion_program_lines/select?${queryParams.toString()}`)
+          }
+          
+          const promoDataPromises = items.map(async (item) => {
+            // const queryParams = new URLSearchParams({ q: `id:${item.id}` })
+            console.log("produk id",item.product_id)
+            
+            try { 
+              if(brand  &&  category){
+                const response = await fetchVariantSolr(`id:${item.product_id} && manufacture_name_s:${brand} && category_name :${category}`);
+                const product = response.response.docs[0];
+                const product_id = product.id
+                console.log("data brand ",brand)
+                console.log("data respon varian ",product)
+                console.log("data ID respon varian ",product_id)
+                const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
+                console.log("data response2 ",response2)
+                return response2;
+              }else if(brand){ // belum bisa menangani lebih dari 1 brand
+                const response = await fetchVariantSolr(`id:${item.product_id} && manufacture_name_s:${brand}`);
+                const product = response.response.docs[0];
+                const product_id = product.id
+                console.log("data brand ",brand)
+                console.log("data respon varian ",product)              
+                console.log("data ID respon varian ",product_id)
+                const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
+                console.log("data response2 ",response2)
+                return response2;
+              }else if (category){ // belum bisa menangani lebih dari 1 category
+                const response = await fetchVariantSolr(`id:${item.product_id} && category_name :${category}`);
+                const product = response.response.docs[0];
+                const product_id = product.id
+                console.log("data brand ",brand)
+                console.log("data respon varian ",product)
+                console.log("data ID respon varian ",product_id)
+                const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
+                return response2;
+              }else{
+                const response = await fetchPromoItemsSolr( `id:${item.id}`)
+                console.log("data respon",response)
+                return response;
+              }
+              // if(brand || category){
+              //   let query = `id:${item.product_id}`;
+              //   if (brand) query += ` OR manufacture_name_s:${brand}`;
+              //   if (category) query += ` OR category_name:${category}`;
+              //   const response = await fetchVariantSolr(query);
+              //   const product = response.response.docs[0];
+              //   const product_id = product.id
+              //   const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
+              //   return response2;
 
-          try {
-            const response = await fetch(`/solr/promotion_program_lines/select?${queryParams.toString()}`)
-            console.log("respon data ", response)
-            if (!response.ok) {
-              throw new Error(`HTTP error! status: ${response.status}`)
-            }
+              // }else{
+              //   const response = await fetchPromoItemsSolr( `id:${item.id}`)
+              //   console.log("data respon",response)
+              //   return response;
+              // }
 
-            const data: SolrResponse<any[]> = await response.json()
-            console.log("data promo IPromotion[]", data)
-            
-            const promotions = await map(data.response.docs)
-            return promotions;
+      
           } catch (fetchError) {
-            console.error("Error fetching promotion data:", fetchError)
+            // console.error("Error fetching promotion data:", fetchError)
             return [];
           }
         });
@@ -68,7 +126,61 @@ export default function PromoDetail() {
         const promoDataArray = await Promise.all(promoDataPromises);
         const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
         setPromoData(mergedPromoData);
-        setTimeout(() => setLoading(false), 120); // Menambahkan delay 120ms sebelum mengubah status loading
+
+        const dataBrandCategoryPromises = promoDataArray.map(async (promoData) => {
+          if (promoData) {
+            const dataBrandCategory = promoData.map(async (item) => {
+              // const response = await fetch(`/solr/variants/select?${queryParams2.toString()}`);
+              let response;
+              if(category){
+                // response = await fetchVariantSolr(`id:${item.products[0].product_id} && manufacture_name_s:${brand}`);
+                response = await fetchVariantSolr(`id:${item.products[0].product_id} && category_name:${category}`);
+              }else{
+                response = await fetchVariantSolr(`id:${item.products[0].product_id}`)    
+              }
+              
+
+              if (response.response?.docs?.length > 0) {
+                const product = response.response.docs[0];
+                const manufactureNameS = product.manufacture_name;
+                if (Array.isArray(manufactureNameS)) {
+                  for (let i = 0; i < manufactureNameS.length; i += 2) {
+                    const brand = manufactureNameS[i];
+                    const qty = 1;
+                    const existingBrandIndex = brandsData.findIndex(b => b.brand === brand);
+                    if (existingBrandIndex !== -1) {
+                      brandsData[existingBrandIndex].qty += qty;
+                    } else {
+                      brandsData.push({ brand, qty });
+                    }
+                  }
+                }
+
+                const categoryNameS = product.category_name;
+                if (Array.isArray(categoryNameS)) {
+                  for (let i = 0; i < categoryNameS.length; i += 2) {
+                    const name = categoryNameS[i];
+                    const qty = 1;
+                    const existingCategoryIndex = categoriesData.findIndex(c => c.name === name);
+                    if (existingCategoryIndex !== -1) {
+                      categoriesData[existingCategoryIndex].qty += qty;
+                    } else {
+                      categoriesData.push({ name, qty });
+                    }
+                  }
+                }
+              }
+            });
+
+            return Promise.all(dataBrandCategory);
+          }
+        });
+
+        await Promise.all(dataBrandCategoryPromises);
+        setBrands(brandsData);
+        setCategories(categoriesData);
+        setLoading(false);
+
       } catch (loadError) {
         console.error("Error loading promo items:", loadError)
         setLoading(false);
@@ -80,13 +192,9 @@ export default function PromoDetail() {
     }
   }, [slug])
 
-  useEffect(() => {
-    window.scrollTo({ top: 0, behavior: 'auto' }); // Auto scroll to top when component mounts or updates
-  }, []); // Run only once when component mounts
-  
   const map = async (promotions: any[]): Promise<IPromotion[]> => {
     const result: IPromotion[] = []
-  
+
     for (const promotion of promotions) {
       const data: IPromotion = {
         id: promotion.id,
@@ -104,67 +212,22 @@ export default function PromoDetail() {
         products: JSON.parse(promotion.products_s),
         free_products: JSON.parse(promotion.free_products_s),
       }
-  
+
       result.push(data)
     }
-  
+
     return result
   }
 
-  console.log("data yg dikirim ke ProductPromoCard", promoData)
   function capitalizeFirstLetter(string) {
-    // Ganti semua tanda _ dengan spasi
     string = string.replace(/_/g, ' ');
-    
-    // Kapitalisasi huruf pertama setelah spasi atau awal string
     return string.replace(/(^\w|\s\w)/g, function(match) {
         return match.toUpperCase();
     });
   }
 
-  useEffect(() => {
-    const handleScroll = () => {
-      if (
-        !fetchingData &&
-        window.innerHeight + document.documentElement.scrollTop >= 0.95 * document.documentElement.offsetHeight
-      ) {
-        // User has scrolled to 95% of page height
-        
-        setTimeout(() => setFetchingData(true), 120);
-        setCurrentPage((prevPage) => prevPage + 1)
-      }
-    }
-
-    window.addEventListener('scroll', handleScroll)
-    return () => window.removeEventListener('scroll', handleScroll)
-  }, [fetchingData])
-
-  useEffect(() => {
-    if (fetchingData) {
-      // Fetch more data
-      // You may need to adjust this logic according to your API
-      fetchMoreData()
-    }
-  }, [fetchingData])
-
-  const fetchMoreData = async () => {
-    try {
-      // Add a delay of approximately 150ms
-      setTimeout(async () => {
-        // Fetch more data
-        // Update promoData state with the new data
-      }, 150)
-    } catch (error) {
-      console.error('Error fetching more data:', error)
-    } finally {
-      setTimeout(() => setFetchingData(false), 120);
-      
-    }
-  }
-  
-    
   const visiblePromotions = promoData?.slice(0, currentPage * 12)
-
+  const isNotReadyStockPage = router.asPath !== '/shop/promo?orderBy=stock';
   return (
     <BasicLayout>
       <Seo
@@ -172,25 +235,25 @@ export default function PromoDetail() {
         description='B2B Marketplace MRO & Industri dengan Layanan Pembayaran Tempo, Faktur Pajak, Online Quotation, Garansi Resmi & Harga Kompetitif'
       />
       <Promocrumb brandName={capitalizeFirstLetter(Array.isArray(slug) ? slug[0] : slug)} /> 
-
+      <ProductFilterDesktop
+              brands={brands || []}
+              categories={categories || []}  
+              prefixUrl={'/shop/promo'}
+              defaultBrand={null}
+            />
       {loading ? (
         <div className='container flex justify-center my-4'>
           <LogoSpinner width={48} height={48} />
         </div>
       ) : promoData && promoItems.length >= 1 ? (
         <>
-          <Swiper slidesPerView={isMobile? 1:4.7} spaceBetween={10} freeMode={true}>
-            <div className=' relative bg-slate-900'>
+          <div className=''>
             {visiblePromotions?.map((promotion) => (
-              <SwiperSlide className='' key={promotion.id}>
-                <div className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
-                  <ProductPromoCard promotion={promotion}/>
-                </div>
-              </SwiperSlide>
+              <div key={promotion.id} className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
+                <ProductPromoCard promotion={promotion}/>
+              </div>
             ))}
-            
           </div>
-          </Swiper>
         </>
       ) : (
         <div className="text-center my-8">
@@ -199,4 +262,4 @@ export default function PromoDetail() {
       )}
     </BasicLayout>
   )
-}
\ No newline at end of file
+}
-- 
cgit v1.2.3


From ef2d3ad6759db8535c04d986f4bc43f01da6ccd8 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Fri, 14 Jun 2024 15:11:13 +0700
Subject: <iman> update promotion-program

---
 src/pages/shop/promo/[slug].tsx | 501 +++++++++++++++++++++++++++++++---------
 1 file changed, 389 insertions(+), 112 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index 1935c61f..70280d1f 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -1,4 +1,5 @@
 import dynamic from 'next/dynamic'
+import NextImage from 'next/image';
 import { useEffect, useState } from 'react'
 import { useRouter } from 'next/router'
 import Seo from '../../../core/components/Seo'
@@ -10,6 +11,7 @@ import { IPromotion } from '../../../../src-migrate/types/promotion'
 import React from 'react'
 import { SolrResponse } from "../../../../src-migrate/types/solr.ts";
 import DesktopView from '../../../core/components/views/DesktopView';
+import MobileView from '../../../core/components/views/MobileView';
 import 'swiper/swiper-bundle.css';
 import useDevice from '../../../core/hooks/useDevice'
 import ProductFilterDesktop from '../../../lib/product/components/ProductFilterDesktop';
@@ -17,22 +19,47 @@ import { HStack, Image, Tag, TagCloseButton, TagLabel } from '@chakra-ui/react';
 import { formatCurrency } from '../../../core/utils/formatValue';
 import Pagination from '../../../core/components/elements/Pagination/Pagination';
 import { cons } from 'lodash-contrib'
+// import SideBanner from '~/modules/side-banner';
+import SideBanner from '../../../../src-migrate/modules/side-banner';
+import whatsappUrl from '../../../core/utils/whatsappUrl';
+import { toQuery } from 'lodash-contrib';
+import _ from 'lodash';
 
 const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout'))
 
 export default function PromoDetail() {
   const router = useRouter()
-  const { slug = '', brand, category } = router.query
+  const { slug = '', brand ='', category='', priceFrom = '', priceTo = '', page = '1' } = router.query
   const [promoItems, setPromoItems] = useState<any[]>([])
   const [promoData, setPromoData] = useState<IPromotion[] | null>(null)
-  const [currentPage, setCurrentPage] = useState(1);
+  const [currentPage, setCurrentPage] = useState(parseInt(page as string, 10) || 1);
   const itemsPerPage = 12; // Jumlah item yang ingin ditampilkan per halaman
-  const startIndex = (currentPage - 1) * itemsPerPage;
-  const endIndex = Math.min(startIndex + itemsPerPage, promoData?.length || 0);
   const [loading, setLoading] = useState(true);
   const { isMobile, isDesktop } = useDevice()
   const [brands, setBrands] = useState<Brand[]>([]);
   const [categories, setCategories] = useState<Category[]>([]);
+  const [brandValues, setBrandValues] = useState<string[]>([]);
+  const [categoryValues, setCategoryValues] = useState<string[]>([]);
+  const [orderBy, setOrderBy] = useState(router.query?.orderBy || 'popular');
+  const [spellings, setSpellings] = useState(null);
+
+  useEffect(() => {
+    // Initialize brandValues based on router.query.brand
+    if (router.query.brand) {
+      const brandsArray = Array.isArray(router.query.brand) ? router.query.brand : [router.query.brand];
+      setBrandValues(brandsArray);
+    } else {
+      setBrandValues([]);
+    }
+
+    // Initialize categoryValues based on router.query.category
+    if (router.query.category) {
+      const categoriesArray = Array.isArray(router.query.category) ? router.query.category : [router.query.category];
+      setCategoryValues(categoriesArray);
+    } else {
+      setCategoryValues([]);
+    }
+  }, [router.query.brand, router.query.category]);
 
   interface Brand {
     brand: string;
@@ -49,11 +76,15 @@ export default function PromoDetail() {
       setLoading(true);
       const brandsData: Brand[] = [];
       const categoriesData: Category[] = [];
-
+      
+      const pageNumber = Array.isArray(page) ? parseInt(page[0], 10) : parseInt(page, 10);
+      setCurrentPage(pageNumber)
       
       try {
-        const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`)
-        setPromoItems(items)
+        // const start = (pageNumber-1) * itemsPerPage;
+        const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`);
+        setPromoItems(items);
+        console.log("promoItems lastIndexOf",promoItems.length)
         
         if (items.length === 0) {
           setPromoData([])
@@ -61,67 +92,76 @@ export default function PromoDetail() {
           return;
           }
           
+          const brandArray = Array.isArray(brand) ? brand : brand.split(',');
+          const categoryArray = Array.isArray(category) ? category : category.split(',');
+          console.log("brandArray",brandArray)
+          console.log("categoryArray",categoryArray)
           const promoDataPromises = items.map(async (item) => {
             // const queryParams = new URLSearchParams({ q: `id:${item.id}` })
             console.log("produk id",item.product_id)
             
             try { 
-              if(brand  &&  category){
-                const response = await fetchVariantSolr(`id:${item.product_id} && manufacture_name_s:${brand} && category_name :${category}`);
-                const product = response.response.docs[0];
-                const product_id = product.id
-                console.log("data brand ",brand)
-                console.log("data respon varian ",product)
-                console.log("data ID respon varian ",product_id)
-                const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
-                console.log("data response2 ",response2)
-                return response2;
-              }else if(brand){ // belum bisa menangani lebih dari 1 brand
-                const response = await fetchVariantSolr(`id:${item.product_id} && manufacture_name_s:${brand}`);
+              let brandQuery = '';
+              if (brand) {
+                brandQuery = brandArray.map(b => `manufacture_name_s:${b}`).join(' OR ');
+                brandQuery = `(${brandQuery})`;
+              }
+  
+              let categoryQuery = '';
+              if (category) {
+                categoryQuery = categoryArray.map(c => `category_name:${c}`).join(' OR ');
+                categoryQuery = `(${categoryQuery})`;
+              }
+  
+              let priceQuery = '';
+              if (priceFrom && priceTo) {
+                priceQuery = `price_f:[${priceFrom} TO ${priceTo}]`;
+              } else if (priceFrom) {
+                priceQuery = `price_f:[${priceFrom} TO *]`;
+              } else if (priceTo) {
+                priceQuery = `price_f:[* TO ${priceTo}]`;
+              }
+  
+              let combinedQuery = '';
+              let combinedQueryPrice = `${priceQuery}`;
+              if (brand && category && priceFrom || priceTo) {
+                combinedQuery = `${brandQuery} AND ${categoryQuery} `;
+              } else if (brand && category) {
+                combinedQuery = `${brandQuery} AND ${categoryQuery}`;
+              } else if (brand && priceFrom || priceTo) {
+                combinedQuery = `${brandQuery}`;
+              } else if (category && priceFrom || priceTo) {
+                combinedQuery = `${categoryQuery}`;
+              } else if (brand) {
+                combinedQuery = brandQuery;
+              } else if (category) {
+                combinedQuery = categoryQuery;
+              } else if (priceFrom || priceTo) {
+              }
+              console.log("combinedQuery",combinedQuery)
+  
+              if (combinedQuery && priceFrom || priceTo) {
+                const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
                 const product = response.response.docs[0];
-                const product_id = product.id
-                console.log("data brand ",brand)
-                console.log("data respon varian ",product)              
-                console.log("data ID respon varian ",product_id)
-                const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
-                console.log("data response2 ",response2)
+                const product_id = product.id;
+                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} AND ${combinedQueryPrice}`); 
+                // const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} `); 
                 return response2;
-              }else if (category){ // belum bisa menangani lebih dari 1 category
-                const response = await fetchVariantSolr(`id:${item.product_id} && category_name :${category}`);
+              }else if(combinedQuery){
+                const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
                 const product = response.response.docs[0];
-                const product_id = product.id
-                console.log("data brand ",brand)
-                console.log("data respon varian ",product)
-                console.log("data ID respon varian ",product_id)
-                const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
+                const product_id = product.id;
+                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} `); 
                 return response2;
-              }else{
-                const response = await fetchPromoItemsSolr( `id:${item.id}`)
-                console.log("data respon",response)
+              } 
+              else {
+                const response = await fetchPromoItemsSolr(`id:${item.id}`);
                 return response;
               }
-              // if(brand || category){
-              //   let query = `id:${item.product_id}`;
-              //   if (brand) query += ` OR manufacture_name_s:${brand}`;
-              //   if (category) query += ` OR category_name:${category}`;
-              //   const response = await fetchVariantSolr(query);
-              //   const product = response.response.docs[0];
-              //   const product_id = product.id
-              //   const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
-              //   return response2;
-
-              // }else{
-              //   const response = await fetchPromoItemsSolr( `id:${item.id}`)
-              //   console.log("data respon",response)
-              //   return response;
-              // }
-
-      
-          } catch (fetchError) {
-            // console.error("Error fetching promotion data:", fetchError)
-            return [];
-          }
-        });
+            } catch (fetchError) {
+              return [];
+            }
+          });
 
         const promoDataArray = await Promise.all(promoDataPromises);
         const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
@@ -130,11 +170,10 @@ export default function PromoDetail() {
         const dataBrandCategoryPromises = promoDataArray.map(async (promoData) => {
           if (promoData) {
             const dataBrandCategory = promoData.map(async (item) => {
-              // const response = await fetch(`/solr/variants/select?${queryParams2.toString()}`);
               let response;
               if(category){
-                // response = await fetchVariantSolr(`id:${item.products[0].product_id} && manufacture_name_s:${brand}`);
-                response = await fetchVariantSolr(`id:${item.products[0].product_id} && category_name:${category}`);
+                const categoryQuery = categoryArray.map(c => `category_name:${c}`).join(' OR ');
+                response = await fetchVariantSolr(`id:${item.products[0].product_id} AND (${categoryQuery})`);
               }else{
                 response = await fetchVariantSolr(`id:${item.products[0].product_id}`)    
               }
@@ -190,34 +229,8 @@ export default function PromoDetail() {
     if (slug) {
       loadPromo()
     }
-  }, [slug])
-
-  const map = async (promotions: any[]): Promise<IPromotion[]> => {
-    const result: IPromotion[] = []
-
-    for (const promotion of promotions) {
-      const data: IPromotion = {
-        id: promotion.id,
-        program_id: promotion.program_id_i,
-        name: promotion.name_s,
-        type: {
-          value: promotion.type_value_s,
-          label: promotion.type_label_s,
-        },
-        limit: promotion.package_limit_i,
-        limit_user: promotion.package_limit_user_i,
-        limit_trx: promotion.package_limit_trx_i,
-        price: promotion.price_f,
-        total_qty: promotion.total_qty_i,
-        products: JSON.parse(promotion.products_s),
-        free_products: JSON.parse(promotion.free_products_s),
-      }
-
-      result.push(data)
-    }
+  },[slug, brand, category, priceFrom, priceTo, currentPage]);
 
-    return result
-  }
 
   function capitalizeFirstLetter(string) {
     string = string.replace(/_/g, ' ');
@@ -226,40 +239,304 @@ export default function PromoDetail() {
     });
   }
 
-  const visiblePromotions = promoData?.slice(0, currentPage * 12)
+  const handleDeleteFilter = async (source, value) => {
+    let params = {
+      q: router.query.q,
+      orderBy: orderBy,
+      brand: brandValues.join(','),
+      category: categoryValues.join(','),
+      priceFrom: priceFrom || '',
+      priceTo: priceTo || '',
+    };
+
+    let brands = brandValues;
+    let catagories = categoryValues;
+    switch (source) {
+      case 'brands':
+        brands = brandValues.filter((item) => item !== value);
+        params.brand = brands.join(',');
+        await setBrandValues(brands);
+        break;
+      case 'category':
+        catagories = categoryValues.filter((item) => item !== value);
+        params.category = catagories.join(',');
+        await setCategoryValues(catagories);
+        break;
+      case 'price':
+        params.priceFrom = '';  // Setel ke string kosong jika ingin menghapus nilai
+      params.priceTo = '';    // Setel ke string kosong jika ingin menghapus nilai
+      break;
+      case 'delete':
+        params = {
+          q: router.query.q,
+          orderBy: orderBy,
+          brand: '',
+          category: '',
+          priceFrom: '',
+          priceTo: '',
+        };
+        break;
+    }
+
+    handleSubmitFilter(params);
+  };
+  const handleSubmitFilter = (params) => {
+    params = _.pickBy(params, _.identity);
+    params = toQuery(params);
+    router.push(`${Array.isArray(slug) ? slug[0] : slug}?${params}`);
+    // router.push(`${Array.isArray(slug) ? slug[0] : slug}`);
+  };
+  const handlePageChange = (selectedPage: number) => {
+    setCurrentPage(selectedPage);
+    router.push(`/shop/promo/${slug}?page=${selectedPage}`);
+  };
+
+  const { search } = router.query;
+  const prefixUrl = `/promo/${slug}`;
+
+  console.log("halaman sekarang", currentPage)
+  console.log("data yang di potong", (currentPage-1) * itemsPerPage, currentPage * 12)
+
+  const visiblePromotions = promoData?.slice( (currentPage-1) * itemsPerPage, currentPage * 12)
+  // const visiblePromotions = promoData?.slice( 0, 12)
   const isNotReadyStockPage = router.asPath !== '/shop/promo?orderBy=stock';
+  const whatPromo = capitalizeFirstLetter(Array.isArray(slug) ? slug[0] : slug)
   return (
     <BasicLayout>
       <Seo
         title={`Promo ${Array.isArray(slug) ? slug[0] : slug} Terkini`} 
         description='B2B Marketplace MRO & Industri dengan Layanan Pembayaran Tempo, Faktur Pajak, Online Quotation, Garansi Resmi & Harga Kompetitif'
       />
-      <Promocrumb brandName={capitalizeFirstLetter(Array.isArray(slug) ? slug[0] : slug)} /> 
-      <ProductFilterDesktop
-              brands={brands || []}
-              categories={categories || []}  
-              prefixUrl={'/shop/promo'}
-              defaultBrand={null}
-            />
-      {loading ? (
-        <div className='container flex justify-center my-4'>
-          <LogoSpinner width={48} height={48} />
-        </div>
-      ) : promoData && promoItems.length >= 1 ? (
-        <>
-          <div className=''>
-            {visiblePromotions?.map((promotion) => (
-              <div key={promotion.id} className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
-                <ProductPromoCard promotion={promotion}/>
+      <Promocrumb brandName={whatPromo} />
+
+      <DesktopView>
+        <div className='container mx-auto flex mb-3'>
+          <div className='w-3/12'>
+          <ProductFilterDesktop
+                  brands={brands || []}
+                  categories={categories || []}  
+                  prefixUrl={'/shop/promo'}
+                  defaultBrand={null}
+                />
+                <div className='h-6' />
+                <SideBanner />
+          </div>
+          <div className='w-9/12 pl-6'>
+            <h1 className='text-2xl mb-2 font-semibold'>Promo {whatPromo}</h1>
+              <FilterChoicesComponent
+                brandValues={brandValues}
+                categoryValues={categoryValues}
+                priceFrom={priceFrom}
+                priceTo={priceTo}
+                handleDeleteFilter={handleDeleteFilter}
+              />
+              {/* <div className='flex justify-between items-center mb-5'>
+                <div className='leading-6 text-gray_r-11'>
+                  {!spellings ? (
+                    <>
+                      Menampilkan&nbsp;
+                      {pageCount > 1 ? (
+                        <>
+                          {productStart + 1}-
+                          {parseInt(productStart) + parseInt(productRows) >
+                          productFound
+                            ? productFound
+                            : parseInt(productStart) + parseInt(productRows)}
+                          &nbsp;dari&nbsp;
+                        </>
+                      ) : (
+                        ''
+                      )}
+                      {productFound}
+                      &nbsp;produk{' '}
+                      {query.q && (
+                        <>
+                          untuk pencarian{' '}
+                          <span className='font-semibold'>{query.q}</span>
+                        </>
+                      )}
+                    </>
+                  ) : (
+                    SpellingComponent
+                  )}
+                </div>
+                <div className='justify-end flex '>
+                  <div className='ml-3'>
+                    <select
+                      name='urutan'
+                      className='form-input'
+                      value={orderBy}
+                      onChange={(e) => handleOrderBy(e)}
+                    >
+                      {orderOptions.map((option, index) => (
+                        <option key={index} value={option.value}>
+                          {' '}
+                          {option.label}{' '}
+                        </option>
+                      ))}
+                    </select>
+                  </div>
+                  <div className='ml-3'>
+                    <select
+                      name='limit'
+                      className='form-input'
+                      value={router.query?.limit || ''}
+                      onChange={(e) => handleLimit(e)}
+                    >
+                      {numRows.map((option, index) => (
+                        <option key={index} value={option}>
+                          {' '}
+                          {option}{' '}
+                        </option>
+                      ))}
+                    </select>
+                  </div>
+                </div>
+              </div> */}
+              {loading ? (
+                <div className='container flex justify-center my-4'>
+                  <LogoSpinner width={48} height={48} />
+                </div>
+              ) : promoData && promoItems.length >= 1 ? (
+                <>
+                <div className='grid grid-cols-3 gap-x-96 gap-y-1'>
+                  {visiblePromotions?.map((promotion) => (
+                    <div key={promotion.id} className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
+                      <ProductPromoCard promotion={promotion}/>
+                    </div>
+                  ))}
+                </div>
+              </>
+              ) : (
+                <div className="text-center my-8">
+                  <p>Belum ada promo pada kategori ini</p>
+                </div>
+              )}          
+              <div className='flex justify-between items-center mt-6 mb-2'>
+                <div className='pt-2 pb-6 flex items-center gap-x-3'>
+                  <NextImage
+                    src='/images/logo-question.png'
+                    alt='Logo Question Indoteknik'
+                    width={60}
+                    height={60}
+                  />
+                  <div className='text-gray_r-12/90'>
+                    <span>
+                      Barang yang anda cari tidak ada?{' '}
+                      <a
+                        href={
+                          router.query?.q
+                            ? whatsappUrl('productSearch', {
+                                name: router.query.q,
+                              })
+                            : whatsappUrl()
+                        }
+                        className='text-danger-500'
+                      >
+                        Hubungi Kami
+                      </a>
+                    </span>
+                  </div>
+                </div>
+
+                <Pagination
+                  pageCount={Math.ceil(promoItems.length/itemsPerPage )}
+                  // pageCount={Math.ceil(5)}
+                  currentPage={currentPage}
+                  url={`${Array.isArray(slug) ? slug[0] : slug}`} 
+                  className='mt-6 mb-2'
+                  />
               </div>
-            ))}
+
           </div>
-        </>
-      ) : (
-        <div className="text-center my-8">
-          <p>Belum ada promo pada kategori ini</p>
         </div>
-      )}
+                  {console.log("promoItems lastIndexOf",promoItems.length)}
+      </DesktopView>
     </BasicLayout>
   )
-}
+  }
+  
+const FilterChoicesComponent = ({
+  brandValues,
+  categoryValues,
+  priceFrom,
+  priceTo,
+  handleDeleteFilter,
+  }) => (
+  <div className='flex items-center'>
+    <HStack spacing={2} className='flex-wrap'>
+      {brandValues?.map((value, index) => (
+        <Tag
+          size='lg'
+          key={index}
+          borderRadius='lg'
+          variant='outline'
+          colorScheme='gray'
+          >
+          <TagLabel>{value}</TagLabel>
+          <TagCloseButton onClick={() => handleDeleteFilter('brands', value)} />
+        </Tag>
+      ))}
+
+      {categoryValues?.map((value, index) => (
+        <Tag
+          size='lg'
+          key={index}
+          borderRadius='lg'
+          variant='outline'
+          colorScheme='gray'
+          >
+          <TagLabel>{value}</TagLabel>
+          <TagCloseButton
+            onClick={() => handleDeleteFilter('category', value)}
+            />
+        </Tag>
+      ))}
+      {priceFrom && priceTo && (
+        <Tag size='lg' borderRadius='lg' variant='outline' colorScheme='gray'>
+          <TagLabel>
+            {formatCurrency(priceFrom) + '-' + formatCurrency(priceTo)}
+          </TagLabel>
+          <TagCloseButton
+            onClick={() => handleDeleteFilter('price', priceFrom)}
+            />
+        </Tag>
+      )}
+      {brandValues?.length > 0 ||
+      categoryValues?.length > 0 ||
+      priceFrom ||
+      priceTo ? (
+        <span>
+          <button
+            className='btn-transparent py-2 px-5 h-[40px] text-red-700'
+            onClick={() => handleDeleteFilter('delete')}
+            >
+            Hapus Semua
+          </button>
+        </span>
+      ) : (
+        ''
+        )}
+    </HStack>
+  </div>
+);
+
+// {loading ? (
+//   <div className='container flex justify-center my-4'>
+//     <LogoSpinner width={48} height={48} />
+//   </div>
+// ) : promoData && promoItems.length >= 1 ? (
+//   <>
+//     <div className=''>
+//       {visiblePromotions?.map((promotion) => (
+//         <div key={promotion.id} className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
+//           <ProductPromoCard promotion={promotion}/>
+//         </div>
+//       ))}
+//     </div>
+//   </>
+// ) : (
+//   <div className="text-center my-8">
+//     <p>Belum ada promo pada kategori ini</p>
+//   </div>
+// )}
\ No newline at end of file
-- 
cgit v1.2.3


From 7c45b1c564db183868b3b99011dd3a090818a285 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Fri, 14 Jun 2024 15:46:41 +0700
Subject: <iman> update promotion program

---
 src/pages/shop/promo/[slug].tsx | 17 +++++++----------
 1 file changed, 7 insertions(+), 10 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index 70280d1f..4f223aed 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -24,6 +24,7 @@ import SideBanner from '../../../../src-migrate/modules/side-banner';
 import whatsappUrl from '../../../core/utils/whatsappUrl';
 import { toQuery } from 'lodash-contrib';
 import _ from 'lodash';
+import { Query } from 'react-query';
 
 const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout'))
 
@@ -283,13 +284,10 @@ export default function PromoDetail() {
   const handleSubmitFilter = (params) => {
     params = _.pickBy(params, _.identity);
     params = toQuery(params);
-    router.push(`${Array.isArray(slug) ? slug[0] : slug}?${params}`);
+    router.push(`${slug}?${params}`);
     // router.push(`${Array.isArray(slug) ? slug[0] : slug}`);
   };
-  const handlePageChange = (selectedPage: number) => {
-    setCurrentPage(selectedPage);
-    router.push(`/shop/promo/${slug}?page=${selectedPage}`);
-  };
+ 
 
   const { search } = router.query;
   const prefixUrl = `/promo/${slug}`;
@@ -300,7 +298,7 @@ export default function PromoDetail() {
   const visiblePromotions = promoData?.slice( (currentPage-1) * itemsPerPage, currentPage * 12)
   // const visiblePromotions = promoData?.slice( 0, 12)
   const isNotReadyStockPage = router.asPath !== '/shop/promo?orderBy=stock';
-  const whatPromo = capitalizeFirstLetter(Array.isArray(slug) ? slug[0] : slug)
+  const whatPromo = capitalizeFirstLetter(slug)
   return (
     <BasicLayout>
       <Seo
@@ -440,12 +438,11 @@ export default function PromoDetail() {
                 </div>
 
                 <Pagination
-                  pageCount={Math.ceil(promoItems.length/itemsPerPage )}
-                  // pageCount={Math.ceil(5)}
+                  pageCount={Math.ceil((promoData?.length ?? 0) / itemsPerPage)}
                   currentPage={currentPage}
-                  url={`${Array.isArray(slug) ? slug[0] : slug}`} 
+                  url={router.asPath.includes('?') ? `${router.asPath}` : `${router.asPath}?`}
                   className='mt-6 mb-2'
-                  />
+                />
               </div>
 
           </div>
-- 
cgit v1.2.3


From 518a2d89d91775ceffd06f8d7aca7050526310da Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Fri, 14 Jun 2024 16:41:13 +0700
Subject: <iman> update add mobile view promotion-program

---
 src/pages/shop/promo/[slug].tsx | 182 ++++++++++++++++------------------------
 1 file changed, 70 insertions(+), 112 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index 4f223aed..c53bcf0e 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -15,16 +15,15 @@ import MobileView from '../../../core/components/views/MobileView';
 import 'swiper/swiper-bundle.css';
 import useDevice from '../../../core/hooks/useDevice'
 import ProductFilterDesktop from '../../../lib/product/components/ProductFilterDesktop';
+import ProductFilter from '../../../lib/product/components/ProductFilter';
 import { HStack, Image, Tag, TagCloseButton, TagLabel } from '@chakra-ui/react';
 import { formatCurrency } from '../../../core/utils/formatValue';
 import Pagination from '../../../core/components/elements/Pagination/Pagination';
-import { cons } from 'lodash-contrib'
-// import SideBanner from '~/modules/side-banner';
 import SideBanner from '../../../../src-migrate/modules/side-banner';
 import whatsappUrl from '../../../core/utils/whatsappUrl';
 import { toQuery } from 'lodash-contrib';
 import _ from 'lodash';
-import { Query } from 'react-query';
+import useActive from '../../../core/hooks/useActive';
 
 const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout'))
 
@@ -43,6 +42,7 @@ export default function PromoDetail() {
   const [categoryValues, setCategoryValues] = useState<string[]>([]);
   const [orderBy, setOrderBy] = useState(router.query?.orderBy || 'popular');
   const [spellings, setSpellings] = useState(null);
+  const popup = useActive();
 
   useEffect(() => {
     // Initialize brandValues based on router.query.brand
@@ -82,10 +82,8 @@ export default function PromoDetail() {
       setCurrentPage(pageNumber)
       
       try {
-        // const start = (pageNumber-1) * itemsPerPage;
         const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`);
         setPromoItems(items);
-        console.log("promoItems lastIndexOf",promoItems.length)
         
         if (items.length === 0) {
           setPromoData([])
@@ -95,11 +93,8 @@ export default function PromoDetail() {
           
           const brandArray = Array.isArray(brand) ? brand : brand.split(',');
           const categoryArray = Array.isArray(category) ? category : category.split(',');
-          console.log("brandArray",brandArray)
-          console.log("categoryArray",categoryArray)
+          
           const promoDataPromises = items.map(async (item) => {
-            // const queryParams = new URLSearchParams({ q: `id:${item.id}` })
-            console.log("produk id",item.product_id)
             
             try { 
               let brandQuery = '';
@@ -137,16 +132,13 @@ export default function PromoDetail() {
                 combinedQuery = brandQuery;
               } else if (category) {
                 combinedQuery = categoryQuery;
-              } else if (priceFrom || priceTo) {
               }
-              console.log("combinedQuery",combinedQuery)
   
               if (combinedQuery && priceFrom || priceTo) {
                 const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
                 const product = response.response.docs[0];
                 const product_id = product.id;
-                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} AND ${combinedQueryPrice}`); 
-                // const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} `); 
+                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} AND ${combinedQueryPrice}`);  
                 return response2;
               }else if(combinedQuery){
                 const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
@@ -154,8 +146,7 @@ export default function PromoDetail() {
                 const product_id = product.id;
                 const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} `); 
                 return response2;
-              } 
-              else {
+              } else {
                 const response = await fetchPromoItemsSolr(`id:${item.id}`);
                 return response;
               }
@@ -222,7 +213,7 @@ export default function PromoDetail() {
         setLoading(false);
 
       } catch (loadError) {
-        console.error("Error loading promo items:", loadError)
+        // console.error("Error loading promo items:", loadError)
         setLoading(false);
       }
     }
@@ -264,8 +255,8 @@ export default function PromoDetail() {
         await setCategoryValues(catagories);
         break;
       case 'price':
-        params.priceFrom = '';  // Setel ke string kosong jika ingin menghapus nilai
-      params.priceTo = '';    // Setel ke string kosong jika ingin menghapus nilai
+        params.priceFrom = '';
+      params.priceTo = '';    
       break;
       case 'delete':
         params = {
@@ -285,19 +276,10 @@ export default function PromoDetail() {
     params = _.pickBy(params, _.identity);
     params = toQuery(params);
     router.push(`${slug}?${params}`);
-    // router.push(`${Array.isArray(slug) ? slug[0] : slug}`);
   };
  
-
-  const { search } = router.query;
-  const prefixUrl = `/promo/${slug}`;
-
-  console.log("halaman sekarang", currentPage)
-  console.log("data yang di potong", (currentPage-1) * itemsPerPage, currentPage * 12)
-
   const visiblePromotions = promoData?.slice( (currentPage-1) * itemsPerPage, currentPage * 12)
-  // const visiblePromotions = promoData?.slice( 0, 12)
-  const isNotReadyStockPage = router.asPath !== '/shop/promo?orderBy=stock';
+ 
   const whatPromo = capitalizeFirstLetter(slug)
   return (
     <BasicLayout>
@@ -306,7 +288,67 @@ export default function PromoDetail() {
         description='B2B Marketplace MRO & Industri dengan Layanan Pembayaran Tempo, Faktur Pajak, Online Quotation, Garansi Resmi & Harga Kompetitif'
       />
       <Promocrumb brandName={whatPromo} />
+      <MobileView>
+        <div className='p-4 pt-0'>
+          <h1 className='mb-2 font-semibold text-h-sm'>Promo {whatPromo}</h1>
+      
+            <FilterChoicesComponent
+                  brandValues={brandValues}
+                  categoryValues={categoryValues}
+                  priceFrom={priceFrom}
+                  priceTo={priceTo}
+                  handleDeleteFilter={handleDeleteFilter}
+                />
+            {promoItems.length >= 1 && (
+            <div className='flex items-center gap-x-2 mb-5 justify-between'>
+              <div>
+                <button
+                  className='btn-light py-2 px-5 h-[40px]'
+                  onClick={popup.activate}
+                >
+                  Filter
+                </button>
+              </div>
+            </div>
+          )}
+          
+          {loading ? (
+                <div className='container flex justify-center my-4'>
+                  <LogoSpinner width={48} height={48} />
+                </div>
+              ) : promoData && promoItems.length >= 1 ? (
+                <>
+                <div className='grid grid-cols-1 gap-x-1 gap-y-1'>
+                  {visiblePromotions?.map((promotion) => (
+                    <div key={promotion.id} className="min-w-[350px] max-w-[350px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
+                      <ProductPromoCard promotion={promotion}/>
+                    </div>
+                  ))}
+                </div>
+              </>
+              ) : (
+                <div className="text-center my-8">
+                  <p>Belum ada promo pada kategori ini</p>
+                </div>
+              )}  
+
+              <Pagination
+                  pageCount={Math.ceil((promoData?.length ?? 0) / itemsPerPage)}
+                  currentPage={currentPage}
+                  url={router.asPath.includes('?') ? `${router.asPath}` : `${router.asPath}?`}
+                  className='mt-6 mb-2'
+                />
+              <ProductFilter
+                active={popup.active}
+                close={popup.deactivate}
+                brands={brands || []}
+                categories={categories || []}
+                prefixUrl={router.asPath.includes('?') ? `${router.asPath}` : `${router.asPath}?`}
+                defaultBrand={null}
+              />
+        </div>
 
+      </MobileView>
       <DesktopView>
         <div className='container mx-auto flex mb-3'>
           <div className='w-3/12'>
@@ -328,69 +370,6 @@ export default function PromoDetail() {
                 priceTo={priceTo}
                 handleDeleteFilter={handleDeleteFilter}
               />
-              {/* <div className='flex justify-between items-center mb-5'>
-                <div className='leading-6 text-gray_r-11'>
-                  {!spellings ? (
-                    <>
-                      Menampilkan&nbsp;
-                      {pageCount > 1 ? (
-                        <>
-                          {productStart + 1}-
-                          {parseInt(productStart) + parseInt(productRows) >
-                          productFound
-                            ? productFound
-                            : parseInt(productStart) + parseInt(productRows)}
-                          &nbsp;dari&nbsp;
-                        </>
-                      ) : (
-                        ''
-                      )}
-                      {productFound}
-                      &nbsp;produk{' '}
-                      {query.q && (
-                        <>
-                          untuk pencarian{' '}
-                          <span className='font-semibold'>{query.q}</span>
-                        </>
-                      )}
-                    </>
-                  ) : (
-                    SpellingComponent
-                  )}
-                </div>
-                <div className='justify-end flex '>
-                  <div className='ml-3'>
-                    <select
-                      name='urutan'
-                      className='form-input'
-                      value={orderBy}
-                      onChange={(e) => handleOrderBy(e)}
-                    >
-                      {orderOptions.map((option, index) => (
-                        <option key={index} value={option.value}>
-                          {' '}
-                          {option.label}{' '}
-                        </option>
-                      ))}
-                    </select>
-                  </div>
-                  <div className='ml-3'>
-                    <select
-                      name='limit'
-                      className='form-input'
-                      value={router.query?.limit || ''}
-                      onChange={(e) => handleLimit(e)}
-                    >
-                      {numRows.map((option, index) => (
-                        <option key={index} value={option}>
-                          {' '}
-                          {option}{' '}
-                        </option>
-                      ))}
-                    </select>
-                  </div>
-                </div>
-              </div> */}
               {loading ? (
                 <div className='container flex justify-center my-4'>
                   <LogoSpinner width={48} height={48} />
@@ -447,7 +426,6 @@ export default function PromoDetail() {
 
           </div>
         </div>
-                  {console.log("promoItems lastIndexOf",promoItems.length)}
       </DesktopView>
     </BasicLayout>
   )
@@ -517,23 +495,3 @@ const FilterChoicesComponent = ({
     </HStack>
   </div>
 );
-
-// {loading ? (
-//   <div className='container flex justify-center my-4'>
-//     <LogoSpinner width={48} height={48} />
-//   </div>
-// ) : promoData && promoItems.length >= 1 ? (
-//   <>
-//     <div className=''>
-//       {visiblePromotions?.map((promotion) => (
-//         <div key={promotion.id} className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
-//           <ProductPromoCard promotion={promotion}/>
-//         </div>
-//       ))}
-//     </div>
-//   </>
-// ) : (
-//   <div className="text-center my-8">
-//     <p>Belum ada promo pada kategori ini</p>
-//   </div>
-// )}
\ No newline at end of file
-- 
cgit v1.2.3


From 55f4e2dc6e25dd425ad0a2b8763f8b8de0305e70 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Fri, 14 Jun 2024 17:08:42 +0700
Subject: <iman> update promotion-program

---
 src/pages/shop/promo/[slug].tsx | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index c53bcf0e..1248ba35 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -45,17 +45,26 @@ export default function PromoDetail() {
   const popup = useActive();
 
   useEffect(() => {
-    // Initialize brandValues based on router.query.brand
     if (router.query.brand) {
-      const brandsArray = Array.isArray(router.query.brand) ? router.query.brand : [router.query.brand];
+      let brandsArray: string[] = [];
+      if (Array.isArray(router.query.brand)) {
+        brandsArray = router.query.brand;
+      } else if (typeof router.query.brand === 'string') {
+        brandsArray = router.query.brand.split(',').map((brand) => brand.trim());
+      }
       setBrandValues(brandsArray);
     } else {
       setBrandValues([]);
     }
 
-    // Initialize categoryValues based on router.query.category
     if (router.query.category) {
-      const categoriesArray = Array.isArray(router.query.category) ? router.query.category : [router.query.category];
+      let categoriesArray: string[] = [];
+
+      if (Array.isArray(router.query.category)) {
+        categoriesArray = router.query.category;
+      } else if (typeof router.query.category === 'string') {
+        categoriesArray = router.query.category.split(',').map((category) => category.trim());
+      }
       setCategoryValues(categoriesArray);
     } else {
       setCategoryValues([]);
@@ -467,6 +476,7 @@ const FilterChoicesComponent = ({
             />
         </Tag>
       ))}
+      {console.log("categoryValues",categoryValues)}
       {priceFrom && priceTo && (
         <Tag size='lg' borderRadius='lg' variant='outline' colorScheme='gray'>
           <TagLabel>
-- 
cgit v1.2.3


From e786215b1be4b88e1b43efb2beae15073d6f81db Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Tue, 18 Jun 2024 08:32:37 +0700
Subject: <iman> update promotion program (handleSubmitFilter)

---
 src/pages/shop/promo/[slug].tsx | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index 1248ba35..da720b16 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -41,7 +41,6 @@ export default function PromoDetail() {
   const [brandValues, setBrandValues] = useState<string[]>([]);
   const [categoryValues, setCategoryValues] = useState<string[]>([]);
   const [orderBy, setOrderBy] = useState(router.query?.orderBy || 'popular');
-  const [spellings, setSpellings] = useState(null);
   const popup = useActive();
 
   useEffect(() => {
@@ -243,7 +242,7 @@ export default function PromoDetail() {
   const handleDeleteFilter = async (source, value) => {
     let params = {
       q: router.query.q,
-      orderBy: orderBy,
+      orderBy: '',
       brand: brandValues.join(','),
       category: categoryValues.join(','),
       priceFrom: priceFrom || '',
@@ -270,7 +269,7 @@ export default function PromoDetail() {
       case 'delete':
         params = {
           q: router.query.q,
-          orderBy: orderBy,
+          orderBy: '',
           brand: '',
           category: '',
           priceFrom: '',
@@ -353,6 +352,7 @@ export default function PromoDetail() {
                 brands={brands || []}
                 categories={categories || []}
                 prefixUrl={router.asPath.includes('?') ? `${router.asPath}` : `${router.asPath}?`}
+                // prefixUrl={`${router.query}?`}
                 defaultBrand={null}
               />
         </div>
-- 
cgit v1.2.3


From 4f4729440befed9899661a5c9a7bc9b57c16cc6e Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Tue, 18 Jun 2024 10:20:30 +0700
Subject: <iman> update grid-cols promotion program

---
 src/pages/shop/promo/[slug].tsx | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index da720b16..19592f6e 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -328,7 +328,7 @@ export default function PromoDetail() {
                 <>
                 <div className='grid grid-cols-1 gap-x-1 gap-y-1'>
                   {visiblePromotions?.map((promotion) => (
-                    <div key={promotion.id} className="min-w-[350px] max-w-[350px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
+                    <div key={promotion.id} className="min-w-[365px] max-w-[365px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
                       <ProductPromoCard promotion={promotion}/>
                     </div>
                   ))}
@@ -385,7 +385,7 @@ export default function PromoDetail() {
                 </div>
               ) : promoData && promoItems.length >= 1 ? (
                 <>
-                <div className='grid grid-cols-3 gap-x-96 gap-y-1'>
+                <div className='grid grid-cols-2 gap-x-36 gap-y-1'>
                   {visiblePromotions?.map((promotion) => (
                     <div key={promotion.id} className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
                       <ProductPromoCard promotion={promotion}/>
-- 
cgit v1.2.3


From 78575ef59454214f61f77b1a826af30497cfdc5f Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Tue, 18 Jun 2024 14:23:16 +0700
Subject: <iman> update url page promotion program

---
 src/pages/shop/promo/[slug].tsx | 22 +++++++++++++++++-----
 1 file changed, 17 insertions(+), 5 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index 19592f6e..667a26ce 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -21,7 +21,7 @@ import { formatCurrency } from '../../../core/utils/formatValue';
 import Pagination from '../../../core/components/elements/Pagination/Pagination';
 import SideBanner from '../../../../src-migrate/modules/side-banner';
 import whatsappUrl from '../../../core/utils/whatsappUrl';
-import { toQuery } from 'lodash-contrib';
+import { cons, toQuery } from 'lodash-contrib';
 import _ from 'lodash';
 import useActive from '../../../core/hooks/useActive';
 
@@ -42,6 +42,7 @@ export default function PromoDetail() {
   const [categoryValues, setCategoryValues] = useState<string[]>([]);
   const [orderBy, setOrderBy] = useState(router.query?.orderBy || 'popular');
   const popup = useActive();
+  const prefixUrl = `/shop/promo/${slug}`
 
   useEffect(() => {
     if (router.query.brand) {
@@ -287,8 +288,18 @@ export default function PromoDetail() {
   };
  
   const visiblePromotions = promoData?.slice( (currentPage-1) * itemsPerPage, currentPage * 12)
+
+  const toQuery = (obj) => {
+    const str = Object.keys(obj)
+      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
+      .join('&')
+    return str
+  }
  
   const whatPromo = capitalizeFirstLetter(slug)
+  const queryWithoutSlug = _.omit(router.query, ['slug'])
+  const queryString = toQuery(queryWithoutSlug)
+  
   return (
     <BasicLayout>
       <Seo
@@ -328,7 +339,7 @@ export default function PromoDetail() {
                 <>
                 <div className='grid grid-cols-1 gap-x-1 gap-y-1'>
                   {visiblePromotions?.map((promotion) => (
-                    <div key={promotion.id} className="min-w-[365px] max-w-[365px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
+                    <div key={promotion.id} className="min-w-[360px] max-w-[360px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
                       <ProductPromoCard promotion={promotion}/>
                     </div>
                   ))}
@@ -343,7 +354,7 @@ export default function PromoDetail() {
               <Pagination
                   pageCount={Math.ceil((promoData?.length ?? 0) / itemsPerPage)}
                   currentPage={currentPage}
-                  url={router.asPath.includes('?') ? `${router.asPath}` : `${router.asPath}?`}
+                  url={`${prefixUrl}?${toQuery(_.omit(queryWithoutSlug, ['page']))}`}
                   className='mt-6 mb-2'
                 />
               <ProductFilter
@@ -352,7 +363,6 @@ export default function PromoDetail() {
                 brands={brands || []}
                 categories={categories || []}
                 prefixUrl={router.asPath.includes('?') ? `${router.asPath}` : `${router.asPath}?`}
-                // prefixUrl={`${router.query}?`}
                 defaultBrand={null}
               />
         </div>
@@ -425,10 +435,12 @@ export default function PromoDetail() {
                   </div>
                 </div>
 
+                
+                
                 <Pagination
                   pageCount={Math.ceil((promoData?.length ?? 0) / itemsPerPage)}
                   currentPage={currentPage}
-                  url={router.asPath.includes('?') ? `${router.asPath}` : `${router.asPath}?`}
+                  url={`${prefixUrl}?${toQuery(_.omit(queryWithoutSlug, ['page']))}`}
                   className='mt-6 mb-2'
                 />
               </div>
-- 
cgit v1.2.3


From ba84659f27c84d0d2c0cc3275e211a865e416bf7 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Wed, 19 Jun 2024 11:31:02 +0700
Subject: <iman> update responsive promotion program

---
 src/pages/shop/promo/[slug].tsx | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index 667a26ce..6e18101f 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -339,7 +339,7 @@ export default function PromoDetail() {
                 <>
                 <div className='grid grid-cols-1 gap-x-1 gap-y-1'>
                   {visiblePromotions?.map((promotion) => (
-                    <div key={promotion.id} className="min-w-[360px] max-w-[360px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
+                    <div key={promotion.id} className="min-w-36 max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
                       <ProductPromoCard promotion={promotion}/>
                     </div>
                   ))}
@@ -395,9 +395,9 @@ export default function PromoDetail() {
                 </div>
               ) : promoData && promoItems.length >= 1 ? (
                 <>
-                <div className='grid grid-cols-2 gap-x-36 gap-y-1'>
+                <div className='grid grid-cols-1 gap-x-20 gap-y-1 lg:gap-x-14  xl:gap-x-36 lg:grid-cols-2 '>
                   {visiblePromotions?.map((promotion) => (
-                    <div key={promotion.id} className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
+                    <div key={promotion.id} className="min-w-[400px] max-w-[400px]  mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
                       <ProductPromoCard promotion={promotion}/>
                     </div>
                   ))}
-- 
cgit v1.2.3


From ced37d32aa345fc288483716771422e7b7c0913a Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Wed, 19 Jun 2024 17:10:24 +0700
Subject: <iman> update tampilan promotion program

---
 src/pages/shop/promo/[slug].tsx | 29 +++++++++++++----------------
 1 file changed, 13 insertions(+), 16 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index 6e18101f..7fea10ff 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -14,7 +14,7 @@ import DesktopView from '../../../core/components/views/DesktopView';
 import MobileView from '../../../core/components/views/MobileView';
 import 'swiper/swiper-bundle.css';
 import useDevice from '../../../core/hooks/useDevice'
-import ProductFilterDesktop from '../../../lib/product/components/ProductFilterDesktop';
+import ProductFilterDesktop from '../../../lib/product/components/ProductFilterDesktopPromotion';
 import ProductFilter from '../../../lib/product/components/ProductFilter';
 import { HStack, Image, Tag, TagCloseButton, TagLabel } from '@chakra-ui/react';
 import { formatCurrency } from '../../../core/utils/formatValue';
@@ -369,19 +369,17 @@ export default function PromoDetail() {
 
       </MobileView>
       <DesktopView>
-        <div className='container mx-auto flex mb-3'>
-          <div className='w-3/12'>
-          <ProductFilterDesktop
-                  brands={brands || []}
-                  categories={categories || []}  
-                  prefixUrl={'/shop/promo'}
-                  defaultBrand={null}
-                />
-                <div className='h-6' />
-                <SideBanner />
-          </div>
-          <div className='w-9/12 pl-6'>
+        <div className='container mx-auto flex mb-3 flex-col'>
+          <div className='w-full pl-6'>
             <h1 className='text-2xl mb-2 font-semibold'>Promo {whatPromo}</h1>
+              <div className=' w-full'>
+                <ProductFilterDesktop
+                      brands={brands || []}
+                      categories={categories || []}  
+                      prefixUrl={'/shop/promo'}
+                      // defaultBrand={null}
+                    />
+                </div>
               <FilterChoicesComponent
                 brandValues={brandValues}
                 categoryValues={categoryValues}
@@ -395,9 +393,9 @@ export default function PromoDetail() {
                 </div>
               ) : promoData && promoItems.length >= 1 ? (
                 <>
-                <div className='grid grid-cols-1 gap-x-20 gap-y-1 lg:gap-x-14  xl:gap-x-36 lg:grid-cols-2 '>
+                <div className='grid grid-cols-1 gap-x-6  sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3'>
                   {visiblePromotions?.map((promotion) => (
-                    <div key={promotion.id} className="min-w-[400px] max-w-[400px]  mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4 ">
+                    <div key={promotion.id} className="min-w-[400px] max-w-[400px]  mb-[20px] sm:min-w-[350px] md:min-w-[380px] lg:min-w-[400px] xl:min-w-[400px] ">
                       <ProductPromoCard promotion={promotion}/>
                     </div>
                   ))}
@@ -488,7 +486,6 @@ const FilterChoicesComponent = ({
             />
         </Tag>
       ))}
-      {console.log("categoryValues",categoryValues)}
       {priceFrom && priceTo && (
         <Tag size='lg' borderRadius='lg' variant='outline' colorScheme='gray'>
           <TagLabel>
-- 
cgit v1.2.3


From fd96f81bdf1ad6bfe8c7a60571eb9ea70f432ff8 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Thu, 20 Jun 2024 11:54:11 +0700
Subject: <iman> update filter promotion-program

---
 src/pages/shop/promo/[slug].tsx | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index 7fea10ff..dbf8d908 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -372,7 +372,7 @@ export default function PromoDetail() {
         <div className='container mx-auto flex mb-3 flex-col'>
           <div className='w-full pl-6'>
             <h1 className='text-2xl mb-2 font-semibold'>Promo {whatPromo}</h1>
-              <div className=' w-full'>
+              <div className=' w-full h-full flex flex-col '>
                 <ProductFilterDesktop
                       brands={brands || []}
                       categories={categories || []}  
@@ -457,7 +457,7 @@ const FilterChoicesComponent = ({
   priceTo,
   handleDeleteFilter,
   }) => (
-  <div className='flex items-center'>
+  <div className='flex items-center mb-4'>
     <HStack spacing={2} className='flex-wrap'>
       {brandValues?.map((value, index) => (
         <Tag
-- 
cgit v1.2.3


From 1cf754b4d8da1aa28700ffc3dad67081f6daf9a5 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Thu, 20 Jun 2024 15:23:58 +0700
Subject: <iman> update filter promotion-program

---
 src/pages/shop/promo/[slug].tsx | 35 +++++++++++++++++++++--------------
 1 file changed, 21 insertions(+), 14 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index dbf8d908..bd69c071 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -372,21 +372,28 @@ export default function PromoDetail() {
         <div className='container mx-auto flex mb-3 flex-col'>
           <div className='w-full pl-6'>
             <h1 className='text-2xl mb-2 font-semibold'>Promo {whatPromo}</h1>
-              <div className=' w-full h-full flex flex-col '>
-                <ProductFilterDesktop
-                      brands={brands || []}
-                      categories={categories || []}  
-                      prefixUrl={'/shop/promo'}
-                      // defaultBrand={null}
-                    />
+              <div className=' w-full h-full flex flex-row items-center '>
+                
+                    <div className='detail-filter w-1/2 flex justify-start items-center  mt-4'>
+
+                  <FilterChoicesComponent
+                    brandValues={brandValues}
+                    categoryValues={categoryValues}
+                    priceFrom={priceFrom}
+                    priceTo={priceTo}
+                    handleDeleteFilter={handleDeleteFilter}
+                  />
+                    </div>
+                    <div className='Filter w-1/2 flex flex-col'>
+
+                    <ProductFilterDesktop
+                          brands={brands || []}
+                          categories={categories || []}  
+                          prefixUrl={'/shop/promo'}
+                          // defaultBrand={null}
+                        />
+                    </div>
                 </div>
-              <FilterChoicesComponent
-                brandValues={brandValues}
-                categoryValues={categoryValues}
-                priceFrom={priceFrom}
-                priceTo={priceTo}
-                handleDeleteFilter={handleDeleteFilter}
-              />
               {loading ? (
                 <div className='container flex justify-center my-4'>
                   <LogoSpinner width={48} height={48} />
-- 
cgit v1.2.3


From 3ada88f0faf901e05bd56ecff8c4bcb209c06787 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Fri, 21 Jun 2024 15:31:12 +0700
Subject: <iman> update all-promotion

---
 src/pages/shop/promo/[slug].tsx | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

(limited to 'src/pages/shop/promo/[slug].tsx')

diff --git a/src/pages/shop/promo/[slug].tsx b/src/pages/shop/promo/[slug].tsx
index bd69c071..aaee1249 100644
--- a/src/pages/shop/promo/[slug].tsx
+++ b/src/pages/shop/promo/[slug].tsx
@@ -91,7 +91,7 @@ export default function PromoDetail() {
       setCurrentPage(pageNumber)
       
       try {
-        const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`);
+        const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`,0,100);
         setPromoItems(items);
         
         if (items.length === 0) {
@@ -147,16 +147,16 @@ export default function PromoDetail() {
                 const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
                 const product = response.response.docs[0];
                 const product_id = product.id;
-                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} AND ${combinedQueryPrice}`);  
+                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} AND ${combinedQueryPrice}`,0,100);  
                 return response2;
               }else if(combinedQuery){
                 const response = await fetchVariantSolr(`id:${item.product_id} AND ${combinedQuery}`);
                 const product = response.response.docs[0];
                 const product_id = product.id;
-                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} `); 
+                const response2 = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug} AND product_ids:${product_id} `,0,100); 
                 return response2;
               } else {
-                const response = await fetchPromoItemsSolr(`id:${item.id}`);
+                const response = await fetchPromoItemsSolr(`id:${item.id}`,0,100);
                 return response;
               }
             } catch (fetchError) {
-- 
cgit v1.2.3

